﻿namespace Manhua2.Pages
{
    using Manhua2.Common;
    using Manhua2.DataModel;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Media.Animation;
    using Windows.UI.Xaml.Media.Imaging;
    using Windows.UI.Xaml.Navigation;
    using Manhua2.Helper;

    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class ViewPageNew : Page
    {
        #region ViewModel
        /// <summary>
        /// 标识 <see cref="DefaultViewModel"/> 依赖属性。
        /// </summary>
        public static readonly DependencyProperty DefaultViewModelProperty =
            DependencyProperty.Register("DefaultViewModel", typeof(IObservableMap<String, Object>),
            typeof(ViewPageNew), null);

        /// <summary>
        /// <see cref="IObservableMap&lt;String, Object&gt;"/> 的实现，该实现旨在
        /// 用作普通视图模型。
        /// </summary>
        public IObservableMap<String, Object> DefaultViewModel
        {
            get
            {
                return this.GetValue(DefaultViewModelProperty) as IObservableMap<String, Object>;
            }

            set
            {
                this.SetValue(DefaultViewModelProperty, value);
            }
        }

        #endregion

        #region 基础数据
        private ViewPageModel config = new ViewPageModel();
        #endregion

        private Chapter chapter;

        private int _curPage;
        public int CurPage
        {
            get { return _curPage; }
            set { _curPage = value; this.OnPageChanged(); }
        }

        private List<ComicPage> pages;

        public ViewPageNew()
        {
            this.InitializeComponent();

            this.DefaultViewModel = new ObservableDictionary<String, Object>();
            this.DefaultViewModel["Config"] = this.config;

            this.direction.IsOn = Global.ClientOption.L2R;
        }

        protected async override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // 退出时保存数据
            if (this.pages == null || this.pages.Count == 0) return;
            try
            {
                using (var context = new ModelContext())
                {
                    var page = this.pages.Where(k => k.Page == this.CurPage).FirstOrDefault();
                    if (page != null)
                        await context.SaveHistoryAsync(this.chapter.ChapterId, page.Page);
                }
            }
            catch
            {
            }
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            string errMsg = null;

            try
            {
                // 接收传递过来的chapter id
                int chapterId = (int)e.Parameter;

                // 加载中...
                this.config.Loading = true;

                using (ModelContext context = new ModelContext())
                {
                    this.chapter = await context.GetChapterAsync(chapterId);

                    // 绑定数据 this.DefaultViewModel
                    // (1) 漫画标题
                    this.DefaultViewModel["ComicTitle"] = chapter.ComicTitle;

                    // (2) 章节标题
                    this.DefaultViewModel["ChapterTitle"] = chapter.ChapterTitle;

                    // (3) 总页数
                    this.DefaultViewModel["TotalPage"] = chapter.TotalPage;

                    // 漫画显示控制
                    this.pages = chapter.Pages;

                    // (4) 当前页数
                    int his = await context.GetHistoryPageAsync(chapterId);
                    if (his == 0)
                    {
                        his = 1;
                        await context.SaveHistoryAsync(chapterId, his);
                    }

                    this.CurPage = his;

                    // 准备就绪，允许点击按钮
                    this.config.IsBtnVisibility = Windows.UI.Xaml.Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
            }

            // 加载完毕
            this.config.Loading = false;

            if (errMsg != null)
                await MethodHelper.ShowMessageDialog(errMsg);
        }
        
        #region 触控操作
        private void OnPageChanged()
        {
            try
            {
                // 特殊情况直接返回
                if (this.pages == null ||
                    this.pages.Count == 0)
                    return;

                this.config.Loading = true;

                // 设置当前页数
                var page = this.pages.Where(k => k.Page == this.CurPage).FirstOrDefault();
                if (page == null) return;

                this.DefaultViewModel["Page"] = page.Page;
                image.Source = new BitmapImage(new Uri(page.SourceUrl));
            }
            catch
            {
            }
        }

        private void Page_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (this.pages == null || this.pages.Count == 0) return;
            var point = e.GetPosition(this);
            if (point.X <= this.ActualWidth / 3)
            {
                if (!this.direction.IsOn)
                {
                    if (this.CurPage > 1)
                        this.CurPage--;
                }
                else
                {
                    if (this.CurPage != this.pages.Count)
                        this.CurPage++;
                }

                return;
            }

            if (point.X >= this.ActualWidth / 3 * 2)
            {
                if (!this.direction.IsOn)
                {
                    if (this.CurPage != this.pages.Count)
                        this.CurPage++;
                }
                else
                {
                    if (this.CurPage > 1)
                        this.CurPage--;
                }

                return;
            }
        }

        private void Page_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
        {
            this.scrollViewer.ZoomToFactor(1.0f);
        }
        #endregion

        private void Image_ImageOpened(object sender, RoutedEventArgs e)
        {
            this.config.Loading = false;
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            MethodHelper.ShowMessageDialog(e.ErrorMessage);
        }

        #region AppbarButton
        private void GoBack(object sender, RoutedEventArgs e)
        {
            if (this.Frame.CanGoBack)
                this.Frame.GoBack();
            else
                this.Frame.Navigate(typeof(MainPage));
        }

        private async void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            if (this.chapter == null)
                return;

            string error = null;

            try
            {
                DownloadItem item = DownloadManager.CreateDownloadItem(
                    this.chapter.ComicTitle,
                    this.chapter.ChapterTitle,
                    this.chapter.TotalPage,
                    this.chapter.Pages.Select(k => k.SourceUrl));

                await DownloadManager.AddToDownloads(item);
                await MethodHelper.ShowMessageDialog("已经添加到下载列表中, 下载完成后请前往\"下载\"文件夹中查看", "提示");
                await DownloadManager.StartDownload(item);
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            await MethodHelper.ShowMessageDialogNotEmpty(error);
        }

        /// <summary>
        /// 返回主页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHome_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage));
        }

        private void btnDetail_Click(object sender, RoutedEventArgs e)
        {
            if (this.chapter == null || this.chapter.ComicId == 0) return;
            this.Frame.Navigate(typeof(ComicDirectoryPage), this.chapter.ComicId);
        }

        /// <summary>
        /// 上一章节
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnPrevious_Click(object sender, RoutedEventArgs e)
        {
            if (this.chapter == null || this.chapter.ComicId == 0) return;

            using (ModelContext context = new ModelContext())
            {
                var results = await context.QueryChaptersIdAsync(this.chapter.ComicId);
                var index = results.IndexOf(this.chapter.ChapterId);

                if (index > 0)
                {
                    this.Frame.Navigate(typeof(ViewPageNew), results[index - 1]);
                }
                else
                {
                    await MethodHelper.ShowMessageDialog("已经到达第一章。", "提示");
                }
            }
        }

        /// <summary>
        /// 下一章节
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnNext_Click(object sender, RoutedEventArgs e)
        {
            if (this.chapter == null || this.chapter.ComicId == 0) return;

            using (ModelContext context = new ModelContext())
            {
                var results = await context.QueryChaptersIdAsync(this.chapter.ComicId);
                var index = results.IndexOf(this.chapter.ChapterId);

                if (index < results.Count - 1)
                {
                    this.Frame.Navigate(typeof(ViewPageNew), results[index + 1]);
                }
                else
                {
                    await MethodHelper.ShowMessageDialog("这已经是最后一章了。", "提示");
                }
            }
        }

        /// <summary>
        /// 图片放大
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZoomIn_Click(object sender, RoutedEventArgs e)
        {
            if (this.pages == null ||
                this.pages.Count == 0)
                return;

            // 计算放大比例
            this.config.Scale += 0.25f;
            this.config.Scale = this.config.Scale > this.config.MaxScale ? this.config.MaxScale: this.config.Scale;
            this.scrollViewer.ZoomToFactor(this.config.Scale);
        }

        /// <summary>
        /// 图片缩小
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZoomOut_Click(object sender, RoutedEventArgs e)
        {
            if (this.pages == null ||
                this.pages.Count == 0)
                return;

            // 计算缩小比例
            this.config.Scale -= 0.25f;
            this.config.Scale = this.config.Scale < this.config.MinScale ? this.config.MinScale : this.config.Scale;
            this.scrollViewer.ZoomToFactor(this.config.Scale);
        }

        /// <summary>
        /// 漫画页面跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGo_Click(object sender, RoutedEventArgs e)
        {
            if (this.pages == null ||
                this.pages.Count == 0)
                return;
            int page;
            if (!int.TryParse(this.txtGoPage.Text, out page))
                return;

            if (page > this.pages.Count ||
                page < 1)
                return;

            this.CurPage = page;
        }

        private void btnPreviousPage_Click(object sender, RoutedEventArgs e)
        {
            if (this.pages == null || this.pages.Count == 0) return;
            if (this.CurPage > 1)
                this.CurPage--;
        }

        private void btnNextPage_Click(object sender, RoutedEventArgs e)
        {
            if (this.pages == null || this.pages.Count == 0) return;
            if (this.CurPage < this.pages.Count)
                this.CurPage++;
        }

        private async void btnFavorite_Click(object sender, RoutedEventArgs e)
        {
            if (this.chapter == null) return;

            try
            {
                using (ModelContext context = new ModelContext())
                {
                    await context.SaveFavoriteAsync(this.chapter.ComicId);
                    await MethodHelper.ShowMessageDialog("收藏成功", "提示");
                }
            }
            catch
            {
            }
        }
        #endregion
    }
}
